<?php

class Images extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'images';

    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'id';
    protected $fillable = array('name', 'description', 'extension','active', 'userID_created','userID_modified');
   
    public static function create(array $options = array()) {

        $file = $options['imageData'];
        $extension = $file->getClientOriginalExtension();
        $options['extension'] = $extension;
                
        $image = parent::create($options);
        $rules = array( 'file' => 'image|max:3000');
        
        $validation = \Validator::make(\Input::all(), $rules);
        if ($validation->fails()) {
            return \Response::make($validation->errors->first(), 400);
        }

        $directory = public_path().'/uploads/images';
        $filename = $image->id.".".$extension;

        
        $upload_success = $file->move($directory, $filename);

        if( $upload_success ) {
            return $image;
        } else {
            return false;
        }
    }
    
    
    public function delete(array $options = array()) {
               
        $image = parent::delete($options);
        File::delete($this->path());
    }
    
    public function path() {
        return public_path().'/uploads/images/'.$this->id.".".$this->extension;
    }
    
    public function url() {
        return asset('uploads/images/'.$this->id.".".$this->extension);
    }
}

